package com.shiyipicture.shiyipicturebackend.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.shiyipicture.shiyipicturebackend.config.CosClientConfig;
import com.shiyipicture.shiyipicturebackend.exception.BusinessException;
import com.shiyipicture.shiyipicturebackend.exception.ErrorCode;
import com.shiyipicture.shiyipicturebackend.exception.ThrowUtils;
import com.shiyipicture.shiyipicturebackend.model.dto.file.UploadPictureResult;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


@Service
@Slf4j
@Deprecated
/**
 * 已废弃改用upload模板方法
 */
public class FileManager {
  @Resource
  private CosClientConfig cosClientConfig;

  @Resource
  private CosManager cosManager;

  /**
   * 上传图片
   *
   * @param multipartFile    文件
   * @param uploadPathPrefix 上传路径前缀
   * @return
   */
  public UploadPictureResult uploadPicture(MultipartFile multipartFile,String uploadPathPrefix){
    validPicture(multipartFile);
    String uuid = RandomUtil.randomString(16);
    String originalFileName = multipartFile.getOriginalFilename();
    String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(originalFileName));
    String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
    File file = null;
    try {
      file = File.createTempFile(uploadPath, null);
      multipartFile.transferTo(file);

      PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath,file);
      ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
      UploadPictureResult uploadPictureResult = new UploadPictureResult();
      int picWidth = imageInfo.getWidth();
      int picHeight = imageInfo.getHeight();
      double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
      uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
      uploadPictureResult.setPicName(originalFileName);
      uploadPictureResult.setPicSize(FileUtil.size(file));
      uploadPictureResult.setPicWidth(picWidth);
      uploadPictureResult.setPicHeight(picHeight);
      uploadPictureResult.setPicScale(picScale);
      uploadPictureResult.setPicFormat(imageInfo.getFormat());
      return uploadPictureResult;
    } catch (IOException e) {
      log.error("图片上传处理失败",e);
      throw new BusinessException(ErrorCode.SYSTEM_ERROR,"上传失败");
    }finally {
      this.deleteTempFile(file);
    }
  }

  /**
   * 上传图片通过URL
   * @param fileUrl
   * @param uploadPathPrefix
   * @return
   */
  public UploadPictureResult uploadPictureByUrl(String fileUrl,String uploadPathPrefix){
    // todo
    validPicture(fileUrl);
    String uuid = RandomUtil.randomString(16);
    //todo
//    String originalFileName = fileUrl.getOriginalFilename();
    String originalFileName = FileUtil.mainName(fileUrl);
    String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(originalFileName));
    String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
    File file = null;
    try {
      file = File.createTempFile(uploadPath, null);
//      multipartFile.transferTo(file);
      //todo
      HttpUtil.downloadFile(fileUrl,file);
      PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath,file);
      ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
      UploadPictureResult uploadPictureResult = new UploadPictureResult();
      int picWidth = imageInfo.getWidth();
      int picHeight = imageInfo.getHeight();
      double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
      uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
      uploadPictureResult.setPicName(originalFileName);
      uploadPictureResult.setPicSize(FileUtil.size(file));
      uploadPictureResult.setPicWidth(picWidth);
      uploadPictureResult.setPicHeight(picHeight);
      uploadPictureResult.setPicScale(picScale);
      uploadPictureResult.setPicFormat(imageInfo.getFormat());
      return uploadPictureResult;
    } catch (IOException e) {
      log.error("图片上传处理失败",e);
      throw new BusinessException(ErrorCode.SYSTEM_ERROR,"上传失败");
    }finally {
      this.deleteTempFile(file);
    }
  }

  private void deleteTempFile(File file) {
    if (file == null) {
      return;
    }
    boolean delete = file.delete();
    if (!delete) {
      log.error("file delete error,filePath = {}",file.getAbsolutePath());
    }
  }

  private void validPicture(MultipartFile multipartFile) {
    ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR,"参数不能为空");
    long size = multipartFile.getSize();
    final long ONE_M = 1024 * 1024L;
    ThrowUtils.throwIf(size > 2 * size,ErrorCode.PARAMS_ERROR,"图片大小不能超过2MB");
    String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
    final List<String> ALLOW_FORMAT_LIST = Arrays.asList("jpg","jpeg","png","webg");
    ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix),ErrorCode.PARAMS_ERROR,"图片格式不正确");
  }

  private void validPicture(String fileUrl) {
    ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR,"路径不能为空");
    try {
      // 验证URL格式
      new URL(fileUrl);
      // 2. 校验 URL 协议
      if (!(fileUrl.startsWith("https://") ||fileUrl.startsWith("http://"))) {
        throw new BusinessException(ErrorCode.PARAMS_ERROR,"仅支持https 或 http协议的文件地址");
      }
      HttpResponse response = null;
      // 3. 发送 HEAD 请求以验证文件是否存在
      response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
      if (response.getStatus() != HttpStatus.HTTP_OK) {
        return;
      }
      //校验文件类型
      String contentType = response.header("Content-Type");
      if (StrUtil.isNotBlank(contentType)) {
        final List<String> ALLOW_FORMAT_LIST = Arrays.asList("image/jpg","image/jpeg","image/png","image/webg");
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(contentType.toLowerCase()),ErrorCode.PARAMS_ERROR,"图片格式不正确");
      }
      //校验文件大小
      String contentLengthStr = response.header("Content-Length");
      if (StrUtil.isNotBlank(contentLengthStr)) {
        long size = Long.parseLong(contentLengthStr);
        final long ONE_M = 1024 * 1024L;
        ThrowUtils.throwIf(size > 2 * size,ErrorCode.PARAMS_ERROR,"图片大小不能超过2MB");
      }
    } catch (MalformedURLException e) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR,"路径格式不正确");
    }

  }

}
